package cn.iocoder.yudao.module.pay.order.controller.app;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.idempotent.core.annotation.Idempotent;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.UserIdempotentKeyResolver;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedOrderStatusEnum;
import cn.iocoder.yudao.module.pay.order.dal.dataobject.PayOrderDO;
import cn.iocoder.yudao.module.pay.order.service.PayOrderService;
import cn.iocoder.yudao.module.pay.order.vo.*;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserType;

@Tag(name = "用户 APP - 付款单据")
@RestController
@RequestMapping("/pay/order")
@Validated
@Slf4j
public class AppPayOrderController {

    @Resource
    private PayOrderService payOrderService;

    @GetMapping("/get")
    @Operation(summary = "获得付款单据")
    @PermitAll // 无需登录限制，扫码商家码付款的情况下可能未登录
    public CommonResult<PayOrderSimpleRespVO> getOrder(@Valid AppPayOrderDetailReqVO reqVO) {
        PayOrderDO order = null;
        if (reqVO.getId() != null && reqVO.getId() > 0) {
            order = payOrderService.getOrder(reqVO.getId());
        } else if (StrUtil.isNotBlank(reqVO.getPayNo())) {
            order = payOrderService.getOrderByNo(reqVO.getPayNo());
        } else if (StrUtil.isNotBlank(reqVO.getTradeNo())) {
            order = payOrderService.getOrderByTradeNo(reqVO.getTradeNo());
        }
        if (order == null) {
            return success(null);
        }
        // sync 仅在等待支付
        if (Boolean.TRUE.equals(reqVO.getSync()) && UnifiedOrderStatusEnum.isWaiting(order.getStatus())) {
            payOrderService.syncOrderQuietly(order);
            // 重新查询，因为同步后，可能会有变化
            order = payOrderService.getOrderByTradeNo(order.getTradeNo());
        }
        return success(BeanUtils.toBean(order, PayOrderSimpleRespVO.class));
    }

    @Idempotent(timeout = 5, message = "重复支付，请稍候再试", keyResolver = UserIdempotentKeyResolver.class)
    @PostMapping("/submit")
    @Operation(summary = "发起支付", description = "获得预支付信息。建议前端弹出一个支付结果检测中的对话框，每隔 1-5 秒调用 `get?tradeNo=xxx&sync=true` 接口查询最新支付结果状态")
    @ApiAccessLog(responseEnable = true)
    @PermitAll // 无需登录限制，扫码商家码付款的情况下可能未登录
    public CommonResult<AppPayOrderSubmitRespVO> submitPayOrder(@Valid @RequestBody AppPayOrderSubmitReqVO reqVO) {
        if (reqVO.getChannelExtras() == null) {
            reqVO.setChannelExtras(Maps.newHashMapWithExpectedSize(2));
        }
        // 通过钱包余额支付、微信小程序支付时，默认以当前登录用户的信息进行兜底
        reqVO.getChannelExtras().put("user_id", String.valueOf(getLoginUserId()));
        reqVO.getChannelExtras().put("user_type", String.valueOf(getLoginUserType()));
        PayOrderSubmitRespVO respVO = payOrderService.submitOrder(getLoginUserId(), reqVO);
        return success(BeanUtils.toBean(respVO, AppPayOrderSubmitRespVO.class));
    }

    @RequestMapping(value = "/notify/{channelCode}", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "回调地址", description = "主要用于微服务架构，单体架构已进行内部事件监听")
    @PermitAll // 回调无需登录限制
    @ApiAccessLog(responseEnable = true)
    public String notify(@PathVariable("channelCode") String channelCode, @RequestParam(required = false) Map<String, String> params, @RequestBody(required = false) String body, @RequestHeader(required = false) Map<String, String> headers) {
        return payOrderService.notify(channelCode, params, body, headers);
    }

    @RequestMapping(value = "/redirect/{channelCode}", method = {RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "回调地址", description = "主要用于前端页面跳转")
    @PermitAll // 回调无需登录限制
    @ApiAccessLog(responseEnable = true)
    public String redirect(@PathVariable("channelCode") String channelCode, @RequestParam(required = false) Map<String, String> params, @RequestBody(required = false) String body, @RequestHeader(required = false) Map<String, String> headers) {
        return payOrderService.notify(channelCode, params, body, headers);
    }

    @PostMapping("/close")
    @Operation(summary = "关单")
    @PermitAll // 回调无需登录限制
    public CommonResult<Boolean> close(@RequestParam("tradeNo") String tradeNo) {
        payOrderService.closeOrderByTradeNo(tradeNo);
        return success(true);
    }

}
